package com.zjitc.exception;

import com.zjitc.utils.ResponseResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 处理系统中各种异常，返回统一格式的响应
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理认证异常 (401)
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseResult<Void> handleAuthenticationException(AuthenticationException e) {
        return ResponseResult.unauthorized("认证失败: " + e.getMessage());
    }

    /**
     * 处理权限不足异常 (403)
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseResult<Void> handleAccessDeniedException(AccessDeniedException e) {
        return ResponseResult.forbidden("权限不足: " + e.getMessage());
    }

    /**
     * 处理参数验证异常 (400)
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        return ResponseResult.error(ResponseResult.BAD_REQUEST, "参数错误: " + e.getMessage());
    }

    /**
     * 处理所有其他未捕获的异常 (500)
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<Void> handleGlobalException(Exception e) {
        // 日志记录异常
        e.printStackTrace();
        return ResponseResult.error("服务器内部错误: " + e.getMessage());
    }
} 